package com.company.permission.servlet;

import com.company.permission.util.JsonUtil;
import com.company.permission.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        String methodName = req.getParameter("method");
        if (methodName == null || methodName.trim().isEmpty()) {
            methodName = "execute";
        }

        try {
            Method method = this.getClass().getMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            sendError(resp, "方法调用失败: " + e.getMessage());
        }
    }

    public void execute(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        sendError(resp, "未指定方法");
    }

    protected void sendSuccess(HttpServletResponse resp, Object data) throws IOException {
        resp.getWriter().write(JsonUtil.toJson(Result.success(data)));
    }

    protected void sendError(HttpServletResponse resp, String message) throws IOException {
        resp.getWriter().write(JsonUtil.toJson(Result.error(message)));
    }
}
